<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <!-- 商品列表的Item -->
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //请求参数对象
        queryObj: {
          //查询关键词
          query: '',
          //商品分类ID
          cid: '',
          //页码值
          pagenum: 1,
          //每页显示多少条数据
          pageSize: 10
        },
        goodsList: [],//商品列表数据
        total: 0,//总数量，用来实现分页
        //定义默认图片
        defaulPic: 'https://img1.baidu.com/it/u=1841333429,3927409117&fm=253&fmt=auto&app=138&f=JPEG?w=610&h=500',
        //节流阀,是否正在请求数据
        isloading: false
      };
    },
    methods:{
      //获取商品列表的数据方法
      async getGoodsList(cb){
        //打开节流阀
        this.isloading = true
        const {data:res} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // console.log(res)
         //关闭节流阀
         this.isloading = false
         //只要数据请求完毕，立即按需调用cb()回调函数
         cb && cb()
        if(res.meta.status !== 200) return uni.$showMsg()
        //新旧数据拼接在一起
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
        // uni.$showMsg('请求成功')
        // console.log(res.message.goods)
        // console.log(res.message.total)
        // 
      },
      //点击商品item项，跳转到商品详情页
      gotoDetail(goods){
        uni.navigateTo({
          url:'/subpkg/goods_detail/goods_detail?goods_id = ' + goods.goods_id
        })
      },
    },
    //触底事件
    onReachBottom() {
      //是否还有下一页数据，公式：但前页码值*每页显示多少条数据 >= 总数条数
      if(this.queryObj.pagenum * this.queryObj.pageSize >= this.total) return uni.$showMsg('数据加载完毕！')
      //如果是，则不发起额外的数据请求
      if(this.isloading) return
      //页码值自增+1
      this.queryObj.pagenum++
      //重新获取列表数据
      this.getGoodsList()
    },
    onLoad(options) {
      this.queryObj.query = options.query || ''
      this.queryObj.query = options.cid || ''
      this.getGoodsList()
      // console.log(options)
    },
    onPullDownRefresh() {
      //重置关键数据
      this.queryObj.pagenum = 1,
      this.total = 0,
      this.isloading = false, 
      this.goodsList = [],
      //重新发起数据请求
      this.getGoodsList(() => uni.stopPullDownRefresh())
    }
  }
</script>

<style lang="scss">
  

</style>
